package erwiki.ui.app.admin;

import java.util.ArrayList;
import java.util.List;

//import javax.annotation.PostConstruct;
//import javax.inject.Inject;
//import javax.inject.Named;

import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.core.services.events.IEventBroker;
import org.eclipse.e4.ui.di.UIEventTopic;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.model.application.ui.advanced.MPerspective;
import org.eclipse.e4.ui.model.application.ui.basic.MWindow;
import org.eclipse.e4.ui.model.application.ui.menu.MDirectMenuItem;
import org.eclipse.e4.ui.model.application.ui.menu.MMenu;
import org.eclipse.e4.ui.model.application.ui.menu.MMenuElement;
import org.eclipse.e4.ui.workbench.UIEvents;
import org.eclipse.e4.ui.workbench.UIEvents.EventTags;
import org.eclipse.e4.ui.workbench.modeling.EModelService;
import org.eclipse.swt.widgets.Display;
import org.osgi.framework.FrameworkUtil;
import org.osgi.service.event.Event;

import erwiki.ui.app.admin.handlers.QuitHandler;
import jakarta.annotation.PostConstruct;
import jakarta.inject.Inject;
import jakarta.inject.Named;

public class MenuProcessor {

	@Inject
	private EModelService modelService;

	@Inject
	MApplication application;
	@Inject
	IEventBroker eventBroker;

	// the menu is injected based on the parameter defined in the extension point
	@Inject
	@Named("erwiki.ui.app.admin.menu.customization")
	private MMenu menu1;
	@Inject
	@Named("erwiki.ui.app.admin.menu.workaround1")
	private MMenu menu2;
	@Inject
	@Named("erwiki.ui.app.admin.menu.workaround2")
	private MMenu menu3;

	@PostConstruct
	void init() {

	}

	@Execute
	public void execute(EModelService modelService) {
		// remove the old exit menu entry
		if (!menu1.getChildren().isEmpty()) {
			List<MMenuElement> list = new ArrayList<>();
			for (MMenuElement element : menu1.getChildren()) {
				// use ID instead of label as label is later translated
				if (element.getElementId() != null) {
					if (element.getElementId().contains("exit")) {
						list.add(element);
					}
				}
			}
			menu1.getChildren().removeAll(list);
		}

		// now add a new menu entry
		// :FVK: Каждый запуск приложения - добавляет пункт меню.
		// (они размножаются, и сохраняются в workspace до следующих сессий)
		MDirectMenuItem menuItem = modelService.createModelElement(MDirectMenuItem.class);
		menuItem.setLabel("Another Exit 2");

		Class<QuitHandler> clazz = QuitHandler.class;
		String bundleName = FrameworkUtil.getBundle(clazz).getSymbolicName();
		String className = clazz.getName();
		menuItem.setContributionURI("bundleclass://" + bundleName + "/" + className);
		menu1.getChildren().add(menuItem);
	}

	boolean beView;

	// @UIEventTopic(UIEvents.UILifeCycle.ACTIVATE) Event event) {
	// @UIEventTopic(UIEvents.UIElement.TOPIC_ALL) Event event) {
	@Inject
	@Optional
	private void closeHandler(@UIEventTopic(UIEvents.ElementContainer.TOPIC_SELECTEDELEMENT) Event event) {
		Object newValue = event.getProperty(EventTags.NEW_VALUE);

		// only run this, if the NEW_VALUE is a MPerspective
		if (!(newValue instanceof MPerspective)) {
			return;
		}

		MPerspective perspective = (MPerspective) newValue;
		String perspectiveId = perspective.getElementId();
		String perspectiveLabel = perspective.getLabel();

		// Get the MWindow, where we want to change the label
		MWindow topLevelWindowOfPerspective = modelService.getTopLevelWindowFor(perspective);
		topLevelWindowOfPerspective.setLabel(perspectiveLabel);

		beView = false;
		if (perspectiveId.equals("erwiki.ui.app.admin.perspective.admin")) {
			beView = true;
		}
		// :FVK: System.err.printf("beView = %s\n", beView);
		Display.getDefault().asyncExec(new Runnable() {
			@Override
			public void run() {
				menu1.setVisible(beView);
				menu1.setToBeRendered(beView);
//        		menu2.setVisible(beView);
//        		menu2.setToBeRendered(beView);
//        		menu3.setVisible(beView);
//        		menu3.setToBeRendered(beView);
			}
		});

		/*{// :FVK: -- tmp.
			System.out.println("\n " + perspectiveId);
			System.out.println("---> " + event);
			for (String name : event.getPropertyNames()) {
				System.out.printf("%s=%s\n", name, event.getProperty(name));
			}
		}*/
	}
}
